<template>
	<view class="">
		<view class="content-span" v-if="isTwo">
			<view
				class="content-item flex-half"
				v-for="(item, index) in lastDeviceList"
				@click="goDevice(item.device_sn)"
				:key="index">
				<view
					class="top-span"
					@click="changeTop(item)"
					v-if="lastDeviceList.length > 8">
					<up-avatar
						shape="square"
						size="16"
						src="/static/image/index/isTop.svg"></up-avatar>
					<view
						:class="isTopItem(item.device_sn) ? 'line' : ''"></view>
				</view>
				<view class="title">
					<up-text
						:lines="1"
						:text="item.name ? item.name : item.device_sn"
						style="padding-bottom: 10px"
						bold
						color="#333"
						size="16"></up-text>
				</view>
				<view class="left">
					<view style="z-index: 1">
						<view class="left-text two-left">
							<up-text
								class="texts"
								:text="item.device_sn"
								color="#666"
								size="12"></up-text>
						</view>
						<view class="left-img icons">
							<up-text
								:text="
									item.conn_status == 1
										? getStatus(item.shadow_status)
										: t('index.status')
								"
								:color="
									item.conn_status === 1
										? getStatusColor(item.shadow_status)
										: '#999'
								"
								size="12"></up-text>
							<up-avatar
								shape="square"
								size="18"
								:src="
									`/static/image/index/battery` +
									getBatteryPic(item.battery) +
									`.svg`
								"></up-avatar>
							<up-text
								:text="item.battery + '%'"
								:color="getBatteryColor(item.battery)"
								size="12"></up-text>
						</view>
					</view>
					<view class="two-img">
						<up-image
							width="69"
							mode="widthFix"
							:src="
								`/static/image/index/` +
								getDeviceImg(item.model_id) +
								`.png`
							" />
					</view>
				</view>
			</view>
		</view>
		<view class="content-span" v-if="!isTwo">
			<view
				class="content-item flex-all"
				v-for="(item, index) in lastDeviceList"
				:key="index"
				@click="goDevice(item.device_sn)">
				<view
					class="top-span"
					@click="changeTop(item)"
					v-if="lastDeviceList.length > 4">
					<up-avatar
						shape="square"
						size="16"
						src="/static/image/index/isTop.svg"></up-avatar>
					<view
						:class="
							toppedDevices.includes(item.device_sn) ? 'line' : ''
						"></view>
				</view>
				<view class="one-right">
					<view class="left-img">
						<up-avatar
							shape="square"
							size="18"
							:src="
								`/static/image/index/battery` +
								getBatteryPic(item.battery) +
								`.svg`
							"></up-avatar>
						<text :style="{ color: getBatteryColor(item.battery) }">
							{{ item.battery }}%
						</text>
					</view>
					<view class="title-one">
						<up-text
							:lines="1"
							:text="item.name ? item.name : item.device_sn"
							style="padding-bottom: 10px"
							bold
							color="#333"
							size="16"></up-text>
					</view>

					<view class="left-text">
						<up-text
							:text="item.device_sn"
							color="#666"
							size="12"></up-text>
						<up-text
							style="flex: 0 0 auto; margin-left: 4px"
							:text="
								item.conn_status == 1
									? getStatus(item.shadow_status)
									: t('index.status')
							"
							:color="
								item.conn_status === 1
									? getStatusColor(item.shadow_status)
									: '#999'
							"
							size="12"></up-text>
					</view>
				</view>
				<view class="right">
					<up-image
						:src="
							`/static/image/index/` +
							getDeviceImg(item.model_id) +
							`.png`
						"
						width="138"
						mode="widthFix" />
				</view>
			</view>
		</view>
	</view>
	<TipsModal
		v-if="showTip"
		type="blackTip"
		:contentText="t('confirm.cancelTop')"
		@handleCancel="cancelTip"
		@handleConfirm="conformTip" />
</template>

<script setup lang="ts">
import { getBoundVcus, updateInfo } from "@/service/index";
import { getDeviceImg } from "@/utils/deviceUtils";
import type * as type from "../type";
import { ref, getCurrentInstance, watch } from "vue";
import TipsModal from "@/components/tipsModal/index.vue";
import {
	getBatteryPic,
	getBatteryColor,
	getStatus,
	getStatusColor,
} from "@/utils/deviceUtils";
import { useI18n } from "vue-i18n";
const { locale, t } = useI18n();
const instance: any = getCurrentInstance();
const props = defineProps<{
	lastDeviceList: type.Device[];
	isTwo: boolean;
	toppedDevices: string[];
}>();
watch(
	() => [props.lastDeviceList, props.isTwo, props.toppedDevices],
	() => {
		// 统一处理变化（未来可扩展）
		console.log("props changed");
	},
	{ deep: true }
);
const emit = defineEmits(["updateTopList", "cancelAfter", "updateDevicesTop"]);
const currentCancelTopDevice = ref<string>("");
const goDevice = (device_sn: string) => {
	uni.navigateTo({
		url: `/pages/device/index?device_sn=${device_sn}`,
	});
};
const showTip = ref(false);
const cancelTip = () => {
	showTip.value = false;
};
const isTopItem = (deviceSn: string) => {
	return props.toppedDevices.includes(deviceSn);
};
const updateString = (deviceSn: string): string => {
	const current = props.toppedDevices;
	if (!current || !deviceSn) return current.join(",");
	const pattern = new RegExp(
		`^${deviceSn}$|^${deviceSn},|,${deviceSn}$|,${deviceSn}(?=,)`,
		"g"
	);
	const result = current.join().replace(pattern, "").replace(/,{2,}/g, ",");
	return result.replace(/^,|,$/g, "");
};
const changeTop = async (item: type.Device) => {
	const deviceSn = item.device_sn;
	// 检查是否已置顶
	if (isTopItem(deviceSn)) {
		currentCancelTopDevice.value = deviceSn;
		showTip.value = true;
		return;
	}
	const newToppedDevices: any = props.toppedDevices
		? `${deviceSn},${props.toppedDevices}`
		: deviceSn;
	changeTopApi(deviceSn, newToppedDevices, "toTop");
};
const changeTopApi = async (
	deviceSn: string,
	newToppedDevices: string,
	type: string
) => {
	try {
		const { data } = await updateInfo({
			device_sn: newToppedDevices,
		});
		if (data?.code === 0) {
			// 更新状态
			emit("updateDevicesTop", newToppedDevices);
			if (type == "toTop") {
				emit("updateTopList", deviceSn);
			} else {
				emit("cancelAfter", deviceSn);
			}
			const text =
				type == "toTop" ? t("success.top") : t("success.cancelTop");
			instance.proxy.$message(text, "success");
		} else {
			instance.proxy.$message(
				data?.msg || t("error.operationFailed"),
				"warning"
			);
		}
	} catch (error) {
		const errtext = type == "toTop" ? t("error.top") : t("error.cancelTop");
		instance.proxy.$message(errtext, "error");
	}
};
const conformTip = () => {
	if (!currentCancelTopDevice.value) return;
	const deviceSn = currentCancelTopDevice.value;
	const newToppedDevices = updateString(deviceSn);
	changeTopApi(deviceSn, newToppedDevices, "cancel");
	showTip.value = false;
};
</script>

<style lang="scss" scoped>
.content-span {
	margin-top: 36rpx;
	display: flex;
	gap: 10px;
	flex-wrap: wrap;
	justify-content: space-between;
	.top-span {
		position: absolute;
		top: 5px;
		right: 5px;
		z-index: 10;
		.line {
			position: absolute;
			top: 50%;
			left: -2px;
			right: -2px;
			height: 1px;
			background-color: #484848;
			-webkit-transform: rotate(45deg);
			transform: rotate(45deg);
		}
	}
	.content-item {
		position: relative;
		background-color: #fff;
		padding: 32rpx 12rpx 20rpx 26rpx;
		border-radius: 20rpx;
		box-sizing: border-box;
		box-shadow: 0.5px 2px 5px 1px rgba(0, 0, 0, 0.14);
		display: flex;
	}
	.flex-all {
		width: calc(100% - 5px);
		justify-content: space-between;
	}
	.flex-half {
		width: calc(50% - 5px);
		flex-direction: column;
		.left {
			display: flex;
			flex-direction: column;
			position: relative;
			justify-content: flex-start;
			align-items: flex-start;
			.two-img {
				width: 69px;
				position: absolute;
				right: 0;
				bottom: 0;
			}
		}
		.texts {
			background: #f2f2f2;
			border-radius: 8px;
			padding: 0 4px;
		}
	}
	.left-img {
		margin: 3px 0 4px;
		line-height: 24px;
		align-items: center;
		display: flex;
		flex-wrap: nowrap;
		text {
			font-size: 12px;
			padding-left: 2px;
		}
		:deep(.u-text__value) {
			white-space: nowrap;
		}
	}
	.icons {
		vertical-align: text-bottom;
		margin-bottom: 0;
		height: 22px;
		:deep(.u-text) {
			vertical-align: text-bottom;
			line-height: 22px;
		}
	}
	.left-text {
		display: flex;
		gap: 4px;
	}
	.title {
		flex: 1;
		:deep(.u-text__value) {
			display: inline-block;
			max-width: calc(100% - 10px);
		}
	}
	.one-right {
		width: calc(100% - 157px);
		.left-text {
			justify-content: flex-start;
		}
	}
	.title-one {
		:deep(.u-text__value) {
			display: inline-block;
			width: 100%;
			max-width: 100%;
		}
	}
	.right {
		img {
			height: auto;
		}
	}
}
</style>
